package com.lagou.rpc.provider.server;

import com.alibaba.fastjson.JSONObject;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @author bwcx_jzy
 * @since 2022/2/17
 */
@Service
public class ZookeeperServer {

    private static final String HOST = "172.19.107.2:2181";

    public void registerNode(String ip, int port) throws Exception {
        RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 1);
        // 使用fluent编程风格
        // 独立的命名空间 /base
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(HOST)
                .sessionTimeoutMs(5000)
                .connectionTimeoutMs(3000)
                .retryPolicy(exponentialBackoffRetry)
                // 独立的命名空间 /base
                .namespace("base")
                .build();

        client.start();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("ip", ip);
        jsonObject.put("port", port);
        // 创建节点
        String nowPath = "/lg-curator/" + ip + "-" + port;
        String s = client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL).forPath(nowPath, jsonObject.toString().getBytes(StandardCharsets.UTF_8));
    }
}
